# -*- coding: utf-8 -*-
# @Author: QX
# @File: keywords.py
from time import sleep

import allure
import pymysql
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.wait import WebDriverWait

from core.globalContext import g_context

gc = g_context()
class Keywords:
    def __init__(self,driver):
        self.driver = driver

    @allure.step('单击元素')
    def option_click(self,**kwargs):
        #kwargs ={'定位方式': 'id','目标对象': 'com.zhao.myreader:id/iv_search'}
        if kwargs['定位方式'].lower() == 'id':
            kw = (AppiumBy.ID,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'xpath':
            kw = (AppiumBy.XPATH,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'class':
            kw = (AppiumBy.CLASS_NAME,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'accessibility_id':
            kw = (AppiumBy.ACCESSIBILITY_ID, kwargs['目标对象'])
        self.driver.find_element(*kw).click()

    @allure.step('输入元素')
    def input_context(self,**kwargs):
        if kwargs['定位方式'].lower() == 'id':
            kw = (AppiumBy.ID,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'xpath':
            kw = (AppiumBy.XPATH,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'class':
            kw = (AppiumBy.CLASS_NAME,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'accessibility_id':
            kw = (AppiumBy.ACCESSIBILITY_ID, kwargs['目标对象'])
        self.driver.find_element(*kw).send_keys(kwargs['数据内容'])

    @allure.step('强制等待对应的元素')
    def  wait_sleep(self,**kwargs):
        sleep(int(kwargs['数据内容']))

    @allure.step('显性等待对应的元素')
    def wait_explicit_text(self,**kwargs):
        if kwargs['定位方式'].lower() == 'id':
            kw = (AppiumBy.ID,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'xpath':
            kw = (AppiumBy.XPATH,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'class':
            kw = (AppiumBy.CLASS_NAME,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'accessibility_id':
            kw = (AppiumBy.ACCESSIBILITY_ID, kwargs['目标对象'])
        ele = WebDriverWait(self.driver,2,0.1).until(lambda x : x.find_element(*kw))
        result = ele.text
        gc.set_dict(kwargs['返回结果'], result)
        return result

    @allure.step('获得元素的文本')
    def get_element(self,**kwargs):
        if kwargs['定位方式'].lower() == 'id':
            kw = (AppiumBy.ID,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'xpath':
            kw = (AppiumBy.XPATH,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'class':
            kw = (AppiumBy.CLASS_NAME,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'accessibility_id':
            kw = (AppiumBy.ACCESSIBILITY_ID, kwargs['目标对象'])
        result = self.driver.find_element(*kw).text
        gc.set_dict(kwargs['返回结果'], result)
        return (result)

    @allure.step('获得断言文本')
    def assert_expected_result_text(self,**kwargs):
        if kwargs['定位方式'].lower() == 'id':
            kw = (AppiumBy.ID,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'xpath':
            kw = (AppiumBy.XPATH,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'class':
            kw = (AppiumBy.CLASS_NAME,kwargs['目标对象'])
        if kwargs['定位方式'].lower() == 'accessibility_id':
            kw = (AppiumBy.ACCESSIBILITY_ID, kwargs['目标对象'])
        excepted_result_text = []
        try:
            eles = self.driver.find_element(*kw)
            eles =list(eles)
        except Exception  as e:
            try:
                eles = self.driver.find_elements(*kw)
            except Exception  as e:
                print(e)
        try:
            for ele in eles:
                excepted_result_text.append(ele.text)
        except  Exception  as e:
            assert False, f"没有一本书：{e}"
        gc.set_dict(kwargs['返回结果'],excepted_result_text[0])
        return (excepted_result_text[0])

    @allure.step('文本断言以进行不同的比较操作')
    def assert_text_comparators(self,**kwargs):
        """
                封装断言以进行不同的比较操作。

                参数:
                value (Any): 实际结果。
                expected (Any): 预期的值。
                op_str (str): 操作符的字符串表示（如 '>', '<', '==' 等）。
                message (str, optional): 自定义的错误消息。

                返回:
                None: 如果断言成功，则不返回任何内容。
        """
        comparators ={
            '>': lambda x,y : x > y,
            '>=': lambda x, y: x >= y,
            '<': lambda x, y: x < y,
            '<=': lambda x, y: x <= y,
            '==': lambda x, y: x == y,
            '!=': lambda x, y: x != y,
            'in': lambda x, y: x  in y,
            'not in': lambda x, y: x not in y

        }

        if kwargs['OP_STR']  not in comparators:
            raise ValueError("没有这个操作符号")
        msg =kwargs.get('MESSAGE',None)
        if not comparators[kwargs['OP_STR']](kwargs['VALUE'],kwargs['EXPECTED']):
            if msg:
                raise AssertionError(msg)
            else:
                raise AssertionError("断言失败")

    @allure.step('获得实际的SQL结果')
    def assert_expected_result_sql(self,**kwargs):
        db_config = gc.get_dict("_database")[kwargs["数据库"]]
        con = pymysql.connect(**db_config)
        cur = con.cursor()
        sql = kwargs['数据内容']
        cur.execute(sql)
        sqlresult = cur.fetchall()
        cur.close()
        con.close()
        expected_result_sql = []
        for sqldata  in sqlresult:
            expected_result_sql.append(sqldata[0])
        gc.set_dict(kwargs['返回结果'], expected_result_sql[0])
        return(expected_result_sql[0])









